package com.lei.dao.impl;

import com.lei.dao.TypeDao;
import com.lei.entity.Type;
import com.lei.util.BaseDb;
import com.lei.util.TransBean;

import java.util.List;
import java.util.Map;

/**
 * @author Lei Chu
 * @Date 2020/10/21 18:02
 */
public class TypeDaoImpl implements TypeDao {
    @Override
    public List<Map> getAllType() {
        String sql = "select typeid,typename from t_type";
        return BaseDb.query(sql);
    }

    @Override
    public List<Type> getAllTypeByPage(Type type) {
        StringBuffer sql = new StringBuffer("select t.typeid,typename,count from t_type t left join \n" +
                "(select typeid,count(*) count from t_book GROUP BY typeid) as c on c.typeid = t.typeid where 1 = 1");
        if (type.getTypename()!=null){
            sql.append(" and typename like '%").append(type.getTypename()).append("%'");
        }
        List<Map> query = BaseDb.query(sql + "");
        return TransBean.populate(Type.class,query);
    }

    @Override
    public long getCount(Type type){
        StringBuffer sql = new StringBuffer("select count(*) c from t_type t left join \n" +
                "(select typeid,count(*) count from t_book GROUP BY typeid) as c on c.typeid = t.typeid where 1 = 1");
        if (type.getTypename()!=null){
            sql.append(" and typename like '%").append(type.getTypename()).append("%'");
        }
        List<Map> counts = BaseDb.query(sql + "");
        return (long) counts.get(0).get("c");
    }

    @Override
    public int addType(Type type) {
        String sql = "insert into t_type (typeid,typename) values(null,?)";
        return BaseDb.update(sql,type.getTypename());
    }

    @Override
    public int updateType(Type type) {
        String sql = "update t_type set typename=? where typeid=?";
        return BaseDb.update(sql,type.getTypename(),type.getTypeid());
    }

    @Override
    public Integer getIdByName(String typename) {
        String sql = "select typeid from t_type where typename = ?";
        List<Map> maps = BaseDb.query(sql, typename);
        if (maps.size()>0){
            return (Integer) maps.get(0).get("typeid");
        }
        return null;
    }

    @Override
    public int deleteType(String typeid) {
        String sql = "delete from t_type where typeid = ?";
        return BaseDb.update(sql,typeid);
    }

    @Override
    public List<Map> getAllTypeAndBookCount() {
        String sql = "select typename name,count value FROM t_type t left join (select typeid ,sum(count) count from t_book GROUP BY typeid ) as c on c.typeid= t.typeid";
        return BaseDb.query(sql);
    }

}
